﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Portal.Cms.Bussiness;
using Portal.Web.Utility;
using Portal.Cms.Model;
using Portal.Utility;
using Portal.Web.Model;
using Portal.Core;
using dtSearch32Lib;
using DocumentSearchServiceModel;
using DocumentSearch32Lib;
using Portal.Systems.Model;
using Portal.Workflow.Bussiness;
using Portal.Cms.Utility;
using System.Data;
using System.Collections.ObjectModel;

namespace Portal.Cms.Render
{
    public class UpdateCmsSurveyDataRenderBll
    {
        static string GetPlugInJavascript(string SiteId)
        {
            string ScriptText =
                   "<script language=javascript>\r\n" +
                   
                   "</script>\r\n";
            return ScriptText;
        }


        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string GroupDataId = (string)WebEnvironments.Request(SiteId, "gid");
                string CmsDataId = (string)WebEnvironments.Request(SiteId, "CmsDataId");
                string BackUrl = (string)WebEnvironments.Request(SiteId, "Back");
                if (string.IsNullOrEmpty(BackUrl))
                {
                    BackUrl = "SurveyInputData.aspx?gid=" + GroupDataId;
                }
                //kiem tra xem co trong quy trinh khong da
                string Html =
                   GetPlugInJavascript(SiteId) +
                   DrawUpdateForm(SiteId, GroupDataId, CmsDataId, BackUrl).HtmlContent;

                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut DrawUpdateForm(string SiteId, string GroupDataId, string CmsDataId, string BackUrl)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                GroupDataCls OGroupData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateGroupDataModel(null, SiteId, GroupDataId);
                CmsDataCls OCmsData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateCmsDataModel(null, SiteId, CmsDataId);
                if (OGroupData == null) throw new Exception("Tham số truy cập không hợp lệ. Nhóm tin không tìm thấy!");
                if (OCmsData == null) throw new Exception("Tham số truy cập không hợp lệ. Bài viết không tìm thấy hoặc đã được xóa!");

                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                bool HasStarted = WorkflowUtilities.CheckHasStartWorkflow(SiteId, CmsDataId);
                if (HasStarted == false)
                {
                    //neu chua nam trong quy trinh thi kiem tra binh thuong
                    SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, GroupDataPermission.StaticId, GroupDataPermission.funcAccess, GroupDataId, WebSessionUtility.GetCurrentLoginUser().UserId, true);
                }
                else
                {
                    //net nam trong quy trinh
                    string WorkflowDefId = OCmsData.WorkflowDefId;
                    if (!string.IsNullOrEmpty(WorkflowDefId))//co quy trinh
                    {
                        Portal.Workflow.Bussiness.WorkflowBll.GetWorkflowCls
                              OWorkFlowInfo = WorkflowBll.GetWorkflowActionInfo(OSiteParam.ConnectionString, WorkflowDefId, CmsDataId);
                        //lay thong tin
                        if (OWorkFlowInfo == null)
                        {
                            //neu khong duoc chuyen thi la chua den luot minh
                            throw new Exception("Bài viết đang nằm trong quy trình và bạn không có quyền sửa");
                        }
                        else
                        {
                            if (OWorkFlowInfo.IsViewer)
                            {
                                //da duoc xu ly
                                throw new Exception("Bài viết  trong quy trình và đã được người khác lấy về xử lý bạn không có quyền sửa");
                            }
                        }
                    }
                    else
                    {
                        SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, GroupDataPermission.StaticId, GroupDataPermission.funcAccess, GroupDataId, WebSessionUtility.GetCurrentLoginUser().UserId, true);
                    }
                }


                //string StyleDisp = " style=\"display:none;\"";
                //if (OGroupData.ShowBody)
                //{
                //    StyleDisp = "";
                //}

                string BackScript = "javascript:window.open('SurveyInputData.aspx?gid=" + OGroupData.GroupDataId + "','_self');";
                if (!string.IsNullOrEmpty(BackUrl))
                {
                    BackScript = "javascript:window.open('" + BackUrl + "','_self');";
                }

                //string UploadHandler = "CmsUploadHandler.ashx";
                //if (OGroupData.frkDataTypeId.Equals("document"))
                //{
                //    UploadHandler = "CmsUploadAttachFileHandler.ashx";
                //}
                string Html =
                     "<script language=javascript>\r\n " +

                    "  function ProcessExpandCollapse(Id)\r\n" +
                    "  {\r\n" +
                    "     if(document.getElementById(Id).className=='Collapsed')\r\n" +
                    "     {\r\n" +
                    "         document.getElementById(Id).className='Expanded';\r\n" +
                    "     }\r\n" +
                    "     else\r\n" +
                    "     {\r\n" +
                    "         document.getElementById(Id).className='Collapsed';\r\n" +
                    "     }\r\n" +
                    "  }\r\n" +

                     " function CallSaveCmsData(CloseWindow)\r\n" +
                     " {\r\n" +
                     "      document.getElementById('divCallSaveAddDataProcessing').innerHTML='Tiến hành cập nhật và đánh index tìm kiếm...';\r\n" +
                     "      setTimeout('RealCallSaveCmsData('+CloseWindow+')',10);\r\n" +
                     " }\r\n" +

                     "  function RealCallSaveCmsData(CloseWindow)\r\n" +
                     "  {\r\n" +
                     "      SiteId='" + SiteId + "';\r\n" +
                     "      GroupDataId='" + GroupDataId + "';\r\n" +
                     "      DataId=document.getElementById('txtDataId').value;\r\n" +
                     "      Alias = document.getElementById('txtAlias').value;\r\n" +
                     "      Subject = document.getElementById('txtSubject').value;\r\n" +
                     "      Description = document.getElementById('txtDescription').value;\r\n" +
                     "      SortIndex=document.getElementById('txtSortIndex').value;\r\n" +
                     "      VoteType=document.getElementById('drpSelectVoteType').value;\r\n" +


                     "      MaxAnswer=parseInt(document.getElementById('txtMaxAnswer').value);\r\n" +
                     "      AjaxOut = Portal.Cms.Render.UpdateCmsSurveyDataRenderBll.ServerSideCreateAnswerTextObject(SiteId, MaxAnswer).value;\r\n" +
                     "      CmsVoteAnswerItems=AjaxOut.RetObject;\r\n" +
                     "      for(var iIndex=0;iIndex<MaxAnswer;iIndex++)\r\n" +
                     "      {\r\n" +
                     "          CmsVoteAnswerItems[iIndex].Subject=document.getElementById('txtAnswerItem'+iIndex).value;\r\n" +
                     "          CmsVoteAnswerItems[iIndex].SortIndex=document.getElementById('txtSortIndex'+iIndex).value;\r\n" +
                     "      }\r\n" +

                     "      AjaxOut = Portal.Cms.Render.UpdateCmsSurveyDataRenderBll.ServerSideSave(SiteId, GroupDataId, DataId, Alias, Subject, Description, VoteType, SortIndex, CmsVoteAnswerItems).value;\r\n" +
                     "      document.getElementById('divCallSaveAddDataProcessing').innerHTML='';\r\n" +
                     "      if(AjaxOut.Error)\r\n" +
                     "      {\r\n" +
                     "          alert(AjaxOut.InfoMessage);\r\n" +
                     "          return;\r\n" +
                     "      }\r\n" +
                     "      if(CloseWindow==1)\r\n"+
                     "      {\r\n"+
                     "          window.open('SurveyInputData.aspx?gid="+GroupDataId+"','_self');\r\n"+
                     "      }\r\n"+
                     "      else\r\n"+
                     "      {\r\n"+
                     "          window.open(AjaxOut.RetUrl,'_self');\r\n" +
                     "      }\r\n"+
                     "  }\r\n" +
                     "</script>\r\n";

                
                string SelectVoteType = "";
                if (OGroupData.frkDataTypeId.Equals("vote"))
                {
                    SelectVoteType = " <select id=drpSelectVoteType>\r\n" +
                                     "      <option value=\"one\">Chỉ chọn 1 phương án</option>\r\n" +
                                     "      <option value=\"two\">Chọn nhiều phương án</option>\r\n" +
                                     "      <option value=\"text\">Nhập text</option>\r\n" +
                                     "      <option value=\"level\">Chọn mức độ tốt, khá, trung bình</option>\r\n" +
                                     "      <option value=\"level1\">Chọn đồng ý, không đồng ý, không ý kiến</option>\r\n" +
                                     " </select>\r\n";
                    if (OCmsData.VoteType.Equals("two"))
                    {
                        SelectVoteType = " <select id=drpSelectVoteType>\r\n" +
                                     "      <option value=\"one\">Chỉ chọn 1 phương án</option>\r\n" +
                                     "      <option selected value=\"two\">Chọn nhiều phương án</option>\r\n" +
                                     "      <option value=\"text\">Nhập text</option>\r\n" +
                                     "      <option value=\"level\">Chọn mức độ tốt, khá, trung bình</option>\r\n" +
                                     "      <option value=\"level1\">Chọn đồng ý, không đồng ý, không ý kiến</option>\r\n" +
                                     " </select>\r\n";
                    }
                    if (OCmsData.VoteType.Equals("text"))
                    {
                        SelectVoteType = " <select id=drpSelectVoteType>\r\n" +
                                     "      <option value=\"one\">Chỉ chọn 1 phương án</option>\r\n" +
                                     "      <option value=\"two\">Chọn nhiều phương án</option>\r\n" +
                                     "      <option selected value=\"text\">Nhập text</option>\r\n" +
                                     "      <option value=\"level\">Chọn mức độ tốt, khá, trung bình</option>\r\n" +
                                     "      <option value=\"level1\">Chọn đồng ý, không đồng ý, không ý kiến</option>\r\n" +
                                     " </select>\r\n";
                    }
                    if (OCmsData.VoteType.Equals("level"))
                    {
                        SelectVoteType = " <select id=drpSelectVoteType>\r\n" +
                                     "      <option value=\"one\">Chỉ chọn 1 phương án</option>\r\n" +
                                     "      <option value=\"two\">Chọn nhiều phương án</option>\r\n" +
                                     "      <option value=\"text\">Nhập text</option>\r\n" +
                                     "      <option selected value=\"level\">Chọn mức độ tốt, khá, trung bình</option>\r\n" +
                                     "      <option value=\"level1\">Chọn đồng ý, không đồng ý, không ý kiến</option>\r\n" +
                                     " </select>\r\n";
                    }
                    if (OCmsData.VoteType.Equals("level1"))
                    {
                        SelectVoteType = " <select id=drpSelectVoteType>\r\n" +
                                     "      <option value=\"one\">Chỉ chọn 1 phương án</option>\r\n" +
                                     "      <option value=\"two\">Chọn nhiều phương án</option>\r\n" +
                                     "      <option value=\"text\">Nhập text</option>\r\n" +
                                     "      <option value=\"level\">Chọn mức độ tốt, khá, trung bình</option>\r\n" +
                                     "      <option selected value=\"level1\">Chọn đồng ý, không đồng ý, không ý kiến</option>\r\n" +
                                     " </select>\r\n";
                    }
                }
                int MaxAnswer = 15;
                CmsDataCls[] AnswerItems = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).ReadingCmsData(SiteId, OCmsData.frkGroupDataId, OCmsData.DataId);
                string ButtonRoot = WebConfig.GetButtonIconRoot(OSiteParam);
                Html +=
                   " <div class=DatabaseFunction>\r\n" +
                   "        <ul>\r\n" +
                   "            <li onclick=\"javascript:CallSaveCmsData(0);\"><img class=image src=\"" + ButtonRoot + "/Save.png\"><div>Ghi lại</div></li>\r\n" +
                   "            <li onclick=\"javascript:CallSaveCmsData(1);\"><img class=image src=\"" + ButtonRoot + "/Save.png\"><div>Ghi lại và đóng</div></li>\r\n" +
                   "            <li onclick=\"" + BackScript + "\"><img class=image src=\"" + ButtonRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                   "        </ul>\r\n" +
                   "  </div>\r\n" +
                   "<div class=CssFormSaveUpdate>\r\n" +
                   "  <input type=hidden id=txtDataId value=\"" + CmsDataId + "\">\r\n" +
                   "  <div id=divCallSaveAddDataProcessing class=CssProcessing></div>\r\n" +
                   "  <table>\r\n" +
                   "    <tr class=\"CssRowAlias\">\r\n" +
                   "        <td class=c1>Mã:</td>\r\n" +
                   "        <td class=c2><input id=txtAlias value=\"" + OCmsData.DataAlias + "\" class=textbox type=textbox></td>\r\n" +
                   "    </tr>\r\n" +
                   "    <tr class=\"CssRowSubject\">\r\n" +
                   "        <td class=c1>Tiêu đề:</td>\r\n" +
                   "        <td class=c2><input id=txtSubject class=textbox type=textbox value=\"" + OCmsData.Subject + "\"></td>\r\n" +
                   "    </tr>\r\n" +

                   "    <tr class=\"CssRowDescription\">\r\n" +
                   "        <td class=c1 style=\"vertical-align:top;\">Nội dung:</td>\r\n" +
                   "        <td class=c2>\r\n" +
                   "               <textarea class=textarea type=textarea id=\"txtDescription\" name=\"txtDescription\">" + OCmsData.Description + "</textarea>\r\n" +
                   "        </td>\r\n" +
                   "    </tr>\r\n" +

                   "    <tr>\r\n" +
                   "        <td class=c1>Loại đánh giá:</td>\r\n" +
                   "        <td class=c2>" + SelectVoteType + "</td>\r\n" +
                   "    </tr>\r\n"+

                   "    <tr class=\"CssRowIndex\">\r\n" +
                   "        <td class=c1>Thứ tự:</td>\r\n" +
                   "        <td class=c2><input style=\"background-color:yellow;\" id=txtSortIndex class=textbox type=textbox value=\"" + OCmsData.SortIndex + "\"></td>\r\n" +
                   "    </tr>\r\n" +
                   "    <tr class=\"CssRowListAnswer\">\r\n" +
                    "        <td class=c1></td>\r\n" +
                    "        <td class=c2>\r\n" +
                    "           <div class=\"CssSurveyAnswer\" id=\"divSurveyAnswer\">\r\n" +
                    "               <input id=\"txtMaxAnswer\" value=\"" + MaxAnswer + "\" type=hidden>\r\n" +
                    "               <div id=divListAnswer>\r\n";
                int StartIndex = 0;
                for (int iIndex = 0; iIndex < MaxAnswer; iIndex++)
                {
                    string SubDataId = "";
                    string Subject = "";
                    if (StartIndex < AnswerItems.Length)
                    {
                        Subject = AnswerItems[StartIndex].Subject;
                        SubDataId = AnswerItems[StartIndex].DataId;
                    }
                    Html += "<div><input style=\"width:30px;\" id=\"txtSortIndex"+iIndex+"\" value=\""+(StartIndex+1)+"\">Phương án " + (iIndex + 1) + "</div>\r\n" +
                            "<div><textarea style=\"height:50px;\" class=textarea type=textarea id=\"txtAnswerItem" + iIndex + "\">" + Subject + "</textarea></div>\r\n";
                    StartIndex++;
                }
                Html +=
                    "               </div>\r\n" +
                    "           </div>\r\n" +
                    "        </td>\r\n" +
                    "    </tr>\r\n" +
                   
                   "  </table>\r\n" +
                   "</div>\r\n";


                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }


        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideSave(
            string SiteId,
            string GroupDataId,
            string DataId,
            string Alias,
            string Subject,
            string Description,
            string VoteType,
            string SortIndex,
            CmsVoteAnswerItemCls[] CmsVoteAnswerItems)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                if (string.IsNullOrEmpty(Subject)) throw new Exception("Chưa nhập tiêu đề dữ liệu!");
               
                CmsDataCls OCmsData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateCmsDataModel(null, SiteId, DataId);
                OCmsData.DataAlias = Alias;
                OCmsData.Subject = Subject;
                OCmsData.OtherSubject = "";
                OCmsData.Description = Description;
                OCmsData.Body = "";
                OCmsData.Source = "";
                OCmsData.Url = "";
                OCmsData.Target = "_self";
                try
                {
                    OCmsData.SortIndex = int.Parse(SortIndex);
                }
                catch { }
                
                OCmsData.VoteType = VoteType;
                CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).SaveCmsData(null, SiteId, DataId, OCmsData, CmsVoteAnswerItems, false);
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideCreateAnswerTextObject(string SiteId, int Max)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            CmsVoteAnswerItemCls[] CmsVoteAnswerItems = new CmsVoteAnswerItemCls[Max];
            for (int iIndex = 0; iIndex < CmsVoteAnswerItems.Length; iIndex++)
            {
                CmsVoteAnswerItems[iIndex] = new CmsVoteAnswerItemCls();
            }
            OAjaxOut.RetObject = CmsVoteAnswerItems;
            return OAjaxOut;
        }
    }
}
